package com.sky.zzh.today;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.onekeyshare.OneKeyShareCallback;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;

import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.widget.sweetdialog.SweetDialog;
import com.sky.widget.sweetdialog.SweetDialog.OnSweetClickListener;
import com.sky.zzh.R;
import com.sky.zzh.SHContainerActivity;
import com.sky.zzh.home.ZZHMainActivity;
import com.sky.zzh.today.gallerydate.MyGallery;
import com.sky.zzh.today.gallerydate.MyGalleryModel;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;
import com.sky.zzh.view.CalendarDialog;
import com.sky.zzh.view.CalendarDialog.CalendarResultListener;
import com.sky.zzh.view.SlidingMenu;

/**
 * 今日数据
 * 
 * @author steveyan
 * 
 */
public class TodayDataFragment extends Fragment implements ITaskListener {
	protected Calendar mInitialTime, minTime = null, maxTime = null;
	protected int mLayoutID;
	protected int minuteInterval;

	// ////////////////////////////////////////////
	private SleepClockCircle mSleepClockCircle;
	private float sleepStartAngle = 0;
	private float sleepEndAngle = 0;
	private LinearLayout llGetUp;
	private LinearLayout llTurnOver;
	private TextView textViewDate;
	private MyOnClickListener listener;
	private TextView tvGetUpRate;
	private TextView tvTurnOverRate;
	private ImageView ic_menology;

	private TextView mTvHour, mTvMin;

	private int lichuang, tidong;
	private String sleeptime = "";

	private Context mContext;

	private SHGet sleepTimeTask;
	private String fromDate, endDate;
	private Calendar calendar;
	// 体动
	private int numGetUp = 0;
	private int numTurnUp = 0;
	private String sleppHour = "12小时";
	private String sleepMinute = "11分";

	private String today = "2015-09-24";
	private String currentSelectDate = "2015-09-24";
	private int selectedYear = 2015;
	private int selectedMonth = 10;
	private int selectedDay = 22;

	private TextView textViewDay;
	private TextView textViewNight;

	private LinearLayout linearLayoutDay, linearLayoutNight;

	private ImageView share;
	private SHGet listTask;

	private MyGallery mMyGallery;

	private RelativeLayout rlSleepChart;

	private double sleepLog = 0.0;

	private ImageView mIvLeftIcon, mIvRightIcon;
	private TextView mTvLeft1, mTvLeft2, mTvRight1, mTvRight2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sleepStartAngle = 0;
		sleepEndAngle = 0;
		listener = new MyOnClickListener();

		calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		selectedYear = year;
		selectedMonth = month;
		selectedDay = day;
		currentSelectDate = today = year + "" + CommonUtil.getDoubleNum(month) + "" + CommonUtil.getDoubleNum(day);
		fromDate = CalendarUtil.getPrevious(year, month, day);
		endDate = today;

		if (CommonUtil.isEmpty(UserInfoManager.getInstance().getUUID())) {
			requestList();
		}
		registerBroadcast();
	}

	private void requestList() {
		listTask = new SHGet();
		listTask.setListener(this);
		listTask.setUrl(ConfigDefinition.URL + "user/UserDeviceList");
		listTask.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
		listTask.start();
	}

	private void requestData(String fromDate, String endDate) {
//		SHDialog.ShowProgressDiaolg(getActivity());
		sleepTimeTask = new SHGet();
		sleepTimeTask.setListener(this);

		// sleepTimeTask.setUrl(ConfigDefinition.URL + "app/SleepQuality");
		// // analyseTask.getTaskArgs().put("UUID",
		// // UserInfoManager.getInstance().getUUID());
		// sleepTimeTask.getTaskArgs().put("UUID", "MT003");
		// System.out.println("UUID:" +
		// UserInfoManager.getInstance().getUUID());
		// sleepTimeTask.getTaskArgs().put("UserId",
		// UserInfoManager.getInstance().getUserId());
		// sleepTimeTask.getTaskArgs().put("FromDate", fromDate);
		// sleepTimeTask.getTaskArgs().put("EndDate", endDate);
		// sleepTimeTask.getTaskArgs().put("FromTime",
		// URLEncoder.encode("18:00"));
		// sleepTimeTask.getTaskArgs().put("EndTime",
		// URLEncoder.encode("06:00"));

		StringBuffer sb = new StringBuffer();
		sb.append(ConfigDefinition.URL + "app/SleepQuality?");
		// sb.append("UUID=MT003");
		sb.append("UUID=" + UserInfoManager.getInstance().getUUID());
		sb.append("&UserId=" + UserInfoManager.getInstance().getUserId());
		sb.append("&FromDate=" + fromDate);
		sb.append("&EndDate=" + endDate);
		sb.append("&FromTime=" + "18:00");
		sb.append("&EndTime=" + "18:00");
		sleepTimeTask.setUrl(sb.toString());
		Log.i("sleepTimeTaskURL", sb.toString());

		sleepTimeTask.start();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mContext = activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_today_data, container, false);
		mSleepClockCircle = (SleepClockCircle) view.findViewById(R.id.sleepClockCircle);
		mSleepClockCircle.setStartEndAngle(sleepStartAngle, sleepEndAngle);
		llGetUp = (LinearLayout) view.findViewById(R.id.llGetUp);
		llTurnOver = (LinearLayout) view.findViewById(R.id.llTurnOver);
		textViewDate = (TextView) view.findViewById(R.id.textViewDate);
		tvTurnOverRate = (TextView) view.findViewById(R.id.tvTurnOverRate);
		tvGetUpRate = (TextView) view.findViewById(R.id.tvGetUpRate);
		mTvHour = (TextView) view.findViewById(R.id.tv_hour);
		mTvMin = (TextView) view.findViewById(R.id.tv_min);
		ic_menology = (ImageView) view.findViewById(R.id.ic_menology_today);
		textViewDay = (TextView) view.findViewById(R.id.textViewDay);

		mIvLeftIcon = (ImageView) view.findViewById(R.id.ivGetUpIcon);
		mIvRightIcon = (ImageView) view.findViewById(R.id.ivTurnOverIcon);
		mTvLeft1 = (TextView) view.findViewById(R.id.tvGetUp);
		mTvRight1 = (TextView) view.findViewById(R.id.tvTurnOver);

		textViewNight = (TextView) view.findViewById(R.id.textViewNight);
		linearLayoutNight = (LinearLayout) view.findViewById(R.id.linearLayoutNight);
		linearLayoutDay = (LinearLayout) view.findViewById(R.id.linearLayoutDay);
		rlSleepChart = (RelativeLayout) view.findViewById(R.id.rlSleepChart);
		share = (ImageView) view.findViewById(R.id.btn_right);
		share.setOnClickListener(listener);
		// llGetUp.setOnClickListener(listener);
		// llTurnOver.setOnClickListener(listener);
		mIvLeftIcon.setOnClickListener(listener);
		mIvRightIcon.setOnClickListener(listener);
		mTvLeft1.setOnClickListener(listener);
		mTvRight1.setOnClickListener(listener);
		tvGetUpRate.setOnClickListener(listener);
		tvTurnOverRate.setOnClickListener(listener);
		ic_menology.setOnClickListener(listener);
		linearLayoutDay.setOnClickListener(listener);
		linearLayoutNight.setOnClickListener(listener);

		mMyGallery = (MyGallery) view.findViewById(R.id.dateGallery);
		this.mMyGallery.setMonSelectedListener(new MyGallery.onSelectedListener() {
			@Override
			public void onSelected(MyGalleryModel model) {
				// TODO 请求网络
				int year = model.getYear();
				int month = model.getMonth();
				int day = model.getDay();
				selectedYear = year;
				selectedMonth = month;
				selectedDay = day;
				endDate = year + "" + CommonUtil.getDoubleNum(month) + "" + CommonUtil.getDoubleNum(day);
				fromDate = CalendarUtil.getPrevious(year, month, day);
				if (!CommonUtil.isEmpty(UserInfoManager.getInstance().getUUID())) {
					requestData(fromDate, endDate);
				}
			}

			@Override
			public void onScroll(MyGalleryModel model) {
				setTitle(model);
			}
		});

		initSliderDate();
		return view;
	}

	private void initSliderDate() {
		mInitialTime = Calendar.getInstance();
	}

	private class MyOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tvGetUp:
			case R.id.tvGetUpRate:
			case R.id.ivGetUpIcon:
				if (!SlidingMenu.isOpen) {
					Intent intent = new Intent(mContext, SHContainerActivity.class);
					intent.putExtra("class", LeaveBedFragment.class.getName());
					intent.putExtra("TYPE", LeaveBedFragment.TYPEGETUP);
					intent.putExtra("times", lichuang);
					intent.putExtra("sleep", sleeptime);
					intent.putExtra("fromDate", fromDate);
					intent.putExtra("endDate", endDate);
					startActivity(intent);
				}
				break;
			case R.id.tvTurnOver:
			case R.id.tvTurnOverRate:
			case R.id.ivTurnOverIcon:
				Intent intent2 = new Intent(mContext, SHContainerActivity.class);
				intent2.putExtra("class", LeaveBedFragment.class.getName());
				intent2.putExtra("TYPE", LeaveBedFragment.TYPETURNUP);
				intent2.putExtra("times", tidong);
				intent2.putExtra("sleep", sleeptime);
				intent2.putExtra("fromDate", fromDate);
				intent2.putExtra("endDate", endDate);
				startActivity(intent2);
				break;
			case R.id.ic_menology_today:
				CalendarDialog dia = new CalendarDialog(getActivity(), new CalendarResultListener() {
					Calendar calendar = Calendar.getInstance();

					@Override
					public void onCalendarResult(Dialog d, String date) {
						// TODO Auto-generated method stub
						d.dismiss();

						String temp_str = "";
						Date dt = new Date();
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						temp_str = format.format(dt);
						if (date.compareTo(temp_str) > 0) {
							Toast.makeText(getActivity(), "日期超出范围了", 1000).show();
						} else {
							try {
								Date dd = format.parse(date);
								calendar.setTime(dd);
								int year = calendar.get(Calendar.YEAR);
								int month = calendar.get(Calendar.MONTH) + 1;
								int day = calendar.get(Calendar.DAY_OF_MONTH);
								String end = calendar.get(Calendar.YEAR) + "" + CommonUtil.getDoubleNum(calendar.get(Calendar.MONTH) + 1) + ""
										+ CommonUtil.getDoubleNum(calendar.get(Calendar.DAY_OF_MONTH));
								String from = CalendarUtil.getPrevious(year, month, day);
								textViewDate.setText(year + "年" + month + "月");

								mMyGallery.setmCalendar(calendar);

							} catch (ParseException e) {
								e.printStackTrace();
							}
						}
					}
				});
				dia.show();
				break;

			case R.id.linearLayoutDay:
				if (!SlidingMenu.isOpen) {
					Intent intent3 = new Intent(getActivity(), SleepPreQualityReport.class);
					intent3.putExtra("fromDate", fromDate);
					intent3.putExtra("endDate", endDate);
					getActivity().startActivity(intent3);
				}
				break;

			case R.id.linearLayoutNight:
				if (!SlidingMenu.isOpen) {
					Intent intent4 = new Intent(getActivity(), SleepQualityReport.class);
					intent4.putExtra("fromDate", fromDate);
					intent4.putExtra("endDate", endDate);
					getActivity().startActivity(intent4);
				}
				break;

			case R.id.btn_right:
				GetandSaveCurrentImage();
				showShare(false, null, false);
				break;

			default:
				break;
			}
		}

	}

	private String getSDCardPath() {
		File sdcardDir = null;
		boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) {
			sdcardDir = Environment.getExternalStorageDirectory();
		}
		return sdcardDir.toString();
	}

	private void showShare(boolean silent, String platform, boolean captureView) {
		final OnekeyShare oks = new OnekeyShare();

		// oks.setAddress("12345678901");
		oks.setTitle("智照护");
		// oks.setTitleUrl("http://mob.com");
		oks.setText("");
		oks.setImagePath(getSDCardPath() + "/zzh/ScreenImages" + "/Screen_share.png");
		// oks.setImagePath(CustomShareFieldsPage.getString("imagePath",
		// MainActivity.TEST_IMAGE));
		// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/05/21/oESpJ78_533x800.jpg");
		// oks.setImageArray(new String[]{MainActivity.TEST_IMAGE,
		// MainActivity.TEST_IMAGE_URL});

		// oks.setUrl("http://www.mob.com");
		// oks.setFilePath(CustomShareFieldsPage.getString("filePath",
		// MainActivity.TEST_IMAGE));
		// oks.setComment(CustomShareFieldsPage.getString("comment",
		// context.getString(R.string.share)));
		// oks.setSite(getActivity().getResources().getString(R.string.app_name));
		// oks.setSiteUrl("http://mob.com");
		// oks.setVenueName(CustomShareFieldsPage.getString("venueName",
		// "ShareSDK"));
		// oks.setVenueDescription(CustomShareFieldsPage.getString("venueDescription",
		// "This is a beautiful place!"));
		// oks.setLatitude(23.056081f);
		// oks.setLongitude(113.385708f);
		oks.setSilent(silent);
		// oks.setShareFromQQAuthSupport(shareFromQQLogin);
		oks.setTheme(OnekeyShareTheme.CLASSIC);

		if (platform != null) {
			oks.setPlatform(platform);
		}

		// 令编辑页面显示为Dialog模式
		oks.setDialogMode();

		// 在自动授权时可以禁用SSO方式
		// if(!CustomShareFieldsPage.getBoolean("enableSSO", true))
		oks.disableSSOWhenAuthorize();

		// 去除注释，则快捷分享的操作结果将通过OneKeyShareCallback回调
		oks.setCallback(new OneKeyShareCallback());

		// 为EditPage设置一个背景的View
		// oks.setEditPageBackground(getPage());
		oks.show(getActivity());
	}

	private void GetandSaveCurrentImage() {
		SHDialog.ShowProgressDiaolg(getActivity(), "正在截图...");
		WindowManager windowManager = getActivity().getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int w = display.getWidth();
		int h = display.getHeight();
		Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		View decorview = getActivity().getWindow().getDecorView();
		decorview.setDrawingCacheEnabled(true);
		Bmp = decorview.getDrawingCache();
		String SavePath = getSDCardPath() + "/zzh/ScreenImages";
		try {
			File path = new File(SavePath);
			String filepath = SavePath + "/Screen_share.png";
			File file = new File(filepath);
			if (!path.exists()) {
				path.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fos = null;
			fos = new FileOutputStream(file);
			if (null != fos) {
				Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
				fos.flush();
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		SHDialog.dismissProgressDiaolg();
	}

	/**
	 * This method sets the title of the dialog
	 */
	protected void setTitle(MyGalleryModel model) {
		if (textViewDate != null) {
			int year = model.getYear();
			int month = model.getMonth();
			int day = model.getDay();
			String text = year + "年" + month + "月";
			textViewDate.setText(text);
		}
	}

	@Override
	public void onTaskFinished(SHTask task) throws Exception {
		JSONObject json = new JSONObject(task.getResult().toString());
		System.out.println("json:" + json);

		System.out.println("UserInfoManager.getInstance().getStartTime():" + UserInfoManager.getInstance().getStartTime());
		System.out.println("UserInfoManager.getInstance().getEndTime():" + UserInfoManager.getInstance().getEndTime());

		if (task == sleepTimeTask) {
			try {
				if ("200".equals(json.optString("ReturnCode"))) {
					SHDialog.dismissProgressDiaolg();
					String bedtimes = json.optString("OutOfBedTimes");
					if (TextUtils.isEmpty(bedtimes)) {
						bedtimes = "0";
					}

					lichuang = Integer.valueOf(bedtimes);

					tvGetUpRate.setText(bedtimes + "次/天");
					String movetimes = json.optString("BodyMovementTimes");
					if (TextUtils.isEmpty(movetimes)) {
						movetimes = "0";
					}

					tidong = Integer.valueOf(movetimes);

					tvTurnOverRate.setText(movetimes + "次/天");
					String ave = json.optString("AverageSleepDuration");
					sleeptime = ave;// 传递到下一个界面
					// if (!"".equals(ave)) {
					// int a = (int) (Double.valueOf(ave) * 60 / 60);
					// mTvHour.setText(a + "");
					// int b = (int) (Double.valueOf(ave) - Double.valueOf(a +
					// "")) * 60;
					// mTvMin.setText(b + "");
					// } else {
					// mTvHour.setText(0 + "");
					// mTvMin.setText(0 + "");
					// }

					if (!TextUtils.isEmpty(ave)) {
						sleepLog = Double.valueOf(ave);
						String[] split = ave.split("\\.");
                        int hour = 0;
                        int minute = 0;
                        hour=Integer.valueOf(split[0]);
						if (split.length>1) {
						  String left = split[1];
				            if (left.length() > 1) {
				                left = left.substring(0, 2);
				            } else {
				                left = left + "0";
				            }
				            minute = Integer.valueOf(left) * 60 / 100;
                        }
						mTvHour.setText(hour + "");
						mTvMin.setText(minute + "");
					} else {
						String start = UserInfoManager.getInstance().getStartTime();
						String end = UserInfoManager.getInstance().getEndTime();
						int hour = 0;
						int minute = 0;
						String[] split1 = start.split(":");
						String[] split2 = end.split(":");

						Integer hourtemp1 = Integer.valueOf(split1[0]);
						Integer hourtemp2 = Integer.valueOf(split2[0]);

						Integer minutetemp1 = Integer.valueOf(split1[1]);
						Integer minutetemp2 = Integer.valueOf(split2[1]);

						hour = hourtemp2 + (24 - hourtemp1);
						if (minutetemp1 + minutetemp2 >= 60) {
							hour++;
							minute = (minutetemp1 + minutetemp2) % 60;
						} else {
							minute = minutetemp1 + minutetemp2;
						}

						sleepLog = minute / 60.0 + hour;
						mTvHour.setText(hour + "");
						mTvMin.setText(minute + "");
					}

					JSONArray array = json.optJSONArray("Data");
					if (array.length() != 0) {
						JSONObject obj = array.getJSONObject(0);
						// int ave = obj.optInt("SleepDuration");
						// int hour = (int) (Double.valueOf(ave) * 60 / 60);
						// int minute = (int) (Double.valueOf(ave) -
						// Double.valueOf(hour + "")) * 60;
						// sleppHour = hour + "小时";
						// sleepMinute = minute + "分";

						String SleepStartTime = obj.optString("SleepStartTime");
						String SleepEndTime = obj.optString("SleepEndTime");
						textViewDay.setText(getHourMinute(SleepEndTime.split(" ")[1]) + "AM");
						textViewNight.setText(getHourMinute(SleepStartTime.split(" ")[1]) + "PM");
						analyseAngle(SleepStartTime, SleepEndTime);
					} else {
						mSleepClockCircle.setStartEndAngle(0, 0);
						textViewDay.setText(UserInfoManager.getInstance().getEndTime() + "AM");
						textViewNight.setText(UserInfoManager.getInstance().getStartTime() + "PM");
						analyseAngle(selectedYear + "-" + selectedMonth + "-" + selectedDay + " " + UserInfoManager.getInstance().getStartTime() + ":00", selectedYear + "-" + selectedMonth + "-"
								+ selectedDay + " " + UserInfoManager.getInstance().getEndTime() + ":00");
					}

				} else {
					SHDialog.dismissProgressDiaolg();
					new SweetDialog(getActivity(), SweetDialog.ERROR_TYPE).setTitleText("提示3").setContentText(json.optString("ErrorMessage")).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (task == listTask) {
			JSONArray deviceArray = json.optJSONArray("DeviceList");
			if (deviceArray.length() == 0) {
				new SweetDialog(getActivity(), SweetDialog.NORMAL_TYPE).setTitleText("提示").setContentText("请到设备管理中添加设备").setConfirmClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetDialog sweetAlertDialog) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setAction("addDevice");
						getActivity().sendBroadcast(intent);
						sweetAlertDialog.dismiss();
					}
				}).show();
			} else {
				for (int i = 0; i < deviceArray.length(); i++) {
					if ("True".equals(deviceArray.getJSONObject(i).getString("IsActivated"))) {
						UserInfoManager.getInstance().setUUID(deviceArray.getJSONObject(i).getString("UUID"));
						UserInfoManager.getInstance().sync(getActivity(), true);
						requestData(fromDate, endDate);
						break;
					}
				}
			}
		}
	}

	private String getHourMinute(String s) {
		String[] split = s.split(":");
		return split[0] + ":" + split[1];
	}

	private void analyseAngle(String SleepStartTime, String SleepEndTime) {
		System.out.println("SleepStartTime:" + SleepStartTime);
		System.out.println("SleepEndTime:" + SleepEndTime);

		int startAngle = 0;
		int endAngle = 0;
		int startAnleHour = getHourFromTime(SleepStartTime);
		int endAngleHour = getHourFromTime(SleepEndTime);
		if (startAnleHour > endAngleHour) {
			startAngle = getAngle(startAnleHour, true);
			endAngle = getDelta(sleepLog);
		} else {
			startAngle = getAngle(startAnleHour, true);
			endAngle = getDelta(sleepLog);
		}
		System.out.println("SleepStartTime:" + startAngle);
		System.out.println("SleepEndTime:" + endAngle);

		sleepStartAngle = startAngle;
		sleepEndAngle = endAngle;
		mSleepClockCircle.setStartEndAngle(sleepStartAngle, sleepEndAngle);

		setPosition(startAngle % 360, linearLayoutDay, true);
		setPosition(getAngle(endAngleHour, true), linearLayoutNight, false);
		// setPosition(360, linearLayoutDay, true);
		// setPosition(360, linearLayoutNight, false);

	}

	private void setPosition(int degree2, View view, boolean isNight) {
		int degree = degree2 % 360;
		int width = rlSleepChart.getWidth();
		int height = rlSleepChart.getHeight();

		int left = (int) rlSleepChart.getX();
		int top = (int) rlSleepChart.getY();
		int bottom = top + rlSleepChart.getHeight();
		int right = left + rlSleepChart.getWidth();

		int x = left + width / 2;
		int y = top + height / 2;

		int d = (int) (width / 2 * Math.cos(degree));
		int e = (int) (width / 2 * Math.sin(degree));

		switch (degree) {
		// cos值，sin值均为正值
		case 0:
			view.setX(x);
			if (!isNight) {
				view.setY(top - view.getHeight() - view.getHeight());
			} else {
				view.setY(top - view.getHeight());
			}
			break;
		case 30:
			e = (int) (width / 2 * Math.sin(degree));
			view.setX(x + view.getWidth() / 2);
			if (!isNight) {
				view.setY(top - view.getHeight() - view.getHeight());
			} else {
				view.setY(top - view.getHeight());
			}
			break;

		case 60:
			view.setX(right - view.getWidth() / 5);
			if (!isNight) {
				view.setY(y - 3 * view.getHeight());
			} else {
				view.setY(y - 4 * view.getHeight());
			}
			break;

		case 90:
			d = (int) (width / 2 * Math.cos(degree));
			e = (int) (width / 2 * Math.sin(degree));
			view.setX(right);
			if (isNight) {
				view.setY(y);
			} else {
				view.setY(y - view.getHeight());
			}
			break;

		case 120:
			view.setX(right);
			if (isNight) {
				view.setY(y + width / 4);
			} else {
				view.setY(y + width / 4 - view.getHeight());
			}
			break;

		case 150:
			view.setX(right - width / 4);
			if (isNight) {
				view.setY(bottom);
			} else {
				view.setY(bottom - view.getHeight());
			}
			break;

		case 180:
			view.setX(x - view.getWidth() / 2);
			if (isNight) {
				view.setY(bottom + view.getHeight() / 4);
			} else {
				view.setY(bottom - view.getHeight() / 2);
			}
			break;

		case 210:
			view.setX(x - view.getWidth() / 2 - width / 4);
			if (isNight) {
				view.setY(bottom);
			} else {
				view.setY(bottom - view.getHeight());
			}
			break;

		case 240:
			view.setX(x - view.getWidth() * 2);
			if (isNight) {
				view.setY(bottom - view.getHeight() * 2);
			} else {
				view.setY(bottom - view.getHeight() * 3);
			}
			break;

		case 270:
			view.setX(left - view.getWidth());
			if (isNight) {
				view.setY(y);
			} else {
				view.setY(y - view.getHeight());
			}
			break;

		case 300:
			view.setX(left - view.getWidth());
			if (isNight) {
				view.setY(y - width / 4);
			} else {
				view.setY(y - width / 4 - view.getHeight());
			}
			break;

		case 330:
			view.setX(left - view.getWidth() / 2);
			if (isNight) {
				view.setY(y - width / 2);
			} else {
				view.setY(y - width / 2 - view.getHeight());
			}
			break;

		}

		// if (0 <= degree & degree < 90) {
		//
		// //cos值，sin值均为正值
		// d = (int) (width / 2 * Math.cos(degree));
		// e = (int) (width / 2 * Math.sin(degree));
		//
		// textviewUP.setX(x + e);
		// textviewUP.setY(y - d - textviewUP.getHeight());
		//
		// }
		// if (90 <= degree & degree < 180) {
		// //cos值为负值，sin值为正值
		// d = (int) (width / 2 * Math.cos(degree));
		// e = (int) (width / 2 * Math.sin(degree));
		//
		// textviewUP.setX(x - d);
		// textviewUP.setY(y + e);
		// }
		// if (180 <= degree & degree < 270) {
		// //cos值为负值，sin值为负值
		// d = (int) (width / 2 * Math.cos(degree));
		// e = (int) (width / 2 * Math.sin(degree));
		//
		// textviewUP.setX(x + d - textviewUP.getWidth());
		// textviewUP.setY(y - e);
		// }
		// if (270 <= degree & degree < 360) {
		// //cos值为正值，sin值为负值
		// d = (int) (width / 2 * Math.cos(degree));
		// e = (int) (width / 2 * Math.sin(degree));
		//
		// textviewUP.setX(x - d - textviewUP.getWidth());
		// textviewUP.setY(y - e - textviewUP.getHeight());
		// }

		// textviewUP.setX(left - textviewUP.getWidth());
		// textviewUP.setY(bottom);
	}

	private int getHourFromTime(String s) {
		String[] split = s.split(" ");
		String[] split2 = split[1].split(":");
		return Integer.valueOf(split2[0]);
	}

	private int getAngle(int hour, boolean isStart) {
		int num = 0;
		switch (hour % 12) {
		case 0:
			num = 0;
			break;
		case 1:
			num = 30;
			break;
		case 2:
			num = 60;
			break;
		case 3:
			num = 90;
			break;
		case 4:
			num = 120;
			break;
		case 5:
			num = 150;
			break;
		case 6:
			num = 180;
			break;
		case 7:
			num = 210;
			break;
		case 8:
			num = 240;
			break;
		case 9:
			num = 270;
			break;
		case 10:
			num = 300;
			break;
		case 11:
			num = 330;
			break;
		case 12:
			num = 360;
			break;

		// case 13:
		// num = 0;
		// break;
		// case 14:
		// num = 30;
		// break;
		// case 15:
		// num = 60;
		// break;
		// case 16:
		// num = 90;
		// break;
		// case 17:
		// num = 120;
		// break;
		// case 18:
		// num = 150;
		// break;
		// case 19:
		// num = 180;
		// break;
		// case 20:
		// num = 210;
		// break;
		// case 21:
		// num = 230;
		// break;
		// case 22:
		// num = 270;
		// break;
		// case 23:
		// num = 300;
		// break;
		// case 24:
		// num = 330;
		// break;

		}
		return num;
	}

	private int getDelta(double d) {
		int delta = 0;
		delta = (int) (30 * d);
		return delta;
	}

	@Override
	public void onTaskFailed(SHTask task) {
	}

	@Override
	public void onTaskUpdateProgress(SHTask task, int count, int total) {
	}

	@Override
	public void onTaskTry(SHTask task) {
	}

	private void registerBroadcast() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("device_change");
	    intentFilter.addAction("update_time");
		getActivity().registerReceiver(rec, intentFilter);
	}

	private BroadcastReceiver rec = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// System.out.println("sssssssssssss");
			requestData(fromDate, endDate);
		}
	};

}
